
const querystring = require('querystring');
const handleBlogRouter = require('./src/router/blog.js');
const handleUserRouter = require('./src/router/user.js');


let SESSION_DATA = {};



const getPostData = (req) => {
    return new Promise((resolve, reject) => {
        if (req.method !== 'POST') {
            resolve({});
            return;
        }
        if (req.headers['content-type'] !== 'application/json') {
            resolve({});
            return;
        }
        let body = '';
        req.on('data', (chunk) => {
            body += chunk.toString();
        });
        req.on('end', () => {
            resolve(body ? JSON.parse(body) : {});
        });
    })
}

const serverHandler = async (req, res) => {
    // 获取cookie
    // const cookie = req.headers.cookie || '';
    // req.cookie = cookie.split(';').map(item => item.trim());
    // req.cookie = req.cookie.map(item => {
    //     return item.split('=');
    // }).reduce((pre, cur) => {
    //     pre[cur[0]] = cur[1];
    //     return pre;
    // }, {});

    // console.log(req.cookie);
    console.log(SESSION_DATA);
    res.setHeader('Content-Type', 'application/json');
    const url = req.url;
    req.query = querystring.parse(url.split('?')[1]);
    const postData = await getPostData(req);
    req.body = postData;

    const blogContent = await handleBlogRouter(req, res);
    if (blogContent) {
        res.end(JSON.stringify(blogContent));
        return;
    }


    const userContent = await handleUserRouter(req, res,SESSION_DATA);
    if (userContent) {
        res.end(JSON.stringify(userContent));
        return;
    }


    res.writeHead(404);
    res.end(JSON.stringify({
        code: 404,
        msg: "404 Not Found"
    }));
}

module.exports = serverHandler;